<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>入库记录</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" label-width="auto" style="width: 100%">
          <!-- 搜索输入框 -->
          <el-form-item>
            <el-input v-model="formInline.keyword" placeholder="单据号/供应商/备注：" clearable />
          </el-form-item>

          <!-- 时间范围选择 -->
          <el-form-item label="日期：">
            <el-date-picker v-model="formInline.dateRange" type="datetimerange" range-separator="-"
              start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" style="width: 340px" clearable />
          </el-form-item>

          <!-- 业务类别 -->
          <el-form-item label="业务：">
            <el-select style="width: 200px" v-model="formInline.type">
              <el-option label="请选择" value="" />
              <el-option label="采购入库" :value="1" />
              <el-option label="退货入库" :value="2" />
              <el-option label="盘盈入库" :value="3" />
              <el-option label="调拨入库" :value="4" />
              <el-option label="其他入库" :value="0" />
            </el-select>
          </el-form-item><br /><br />

          <!-- 业务人员 -->
          <el-form-item label="业务人员：">
            <el-select style="width: 200px" v-model="formInline.staffId">
              <el-option label="请选择" value="" />
              <el-option label="仓库-小衣" value="S1001" />
              <el-option label="仓库-小三" value="S1003" />
              <el-option label="仓库-小五" value="S1005" />
              <el-option label="仓库-小七" value="S1007" />
              <el-option label="仓库-小九" value="S1009" />
            </el-select>
          </el-form-item>

          <!-- 查询按钮 -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 分割线 -->
      <el-divider style="margin: 10px 0" />

      <!-- 表格操作按钮 -->
      <div class="operate-buttons">
        <el-button type="primary" style="height: 25px" @click="router.push({ name: 'editInBound' })">新增</el-button>
        <el-button type="danger" style="height: 25px" @click="deleteInboundList()">删除</el-button>
        <el-button type="success" plain style="height: 25px" @click="auditorInboundList()">审核</el-button>
        <el-button plain style="height: 25px">打印</el-button>
        <el-button plain style="height: 25px" @click="exportFile">导出</el-button>
      </div>

      <!-- 表格数据 -->
      <div class="table">
        <el-table :data="inboundList" style="width: 100%" border empty-text="暂无入库记录" show-summary sum-text="总计"
          v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" />
          <el-table-column fixed prop="code" label="单据编号" width="150" header-align="center" align="center" />
          <el-table-column label="业务类型" width="120" header-align="center" align="center">
            <template #default="{ row }">
              {{ showInboundType(row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalQuantity" label="数量" width="80" header-align="center" align="center" />
          <el-table-column prop="totalMoney" label="金额(元)" width="120" header-align="center" align="center" />
          <el-table-column prop="providerName" label="供应商" width="200" header-align="center" align="center" />
          <el-table-column prop="staffName" label="业务员" width="100" header-align="center" align="center" />
          <!-- <el-table-column prop="staffNo" label="制单人" width="100" header-align="center" align="center" /> -->
          <el-table-column prop="auditorName" label="审核人" width="100" header-align="center" align="center" />
          <el-table-column label="状态" width="120" align="center">
            <template #default="{ row }">
              {{ showInboundStatus(row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="printNumber" label="打印次数" width="100" header-align="center" align="center" />

          <el-table-column fixed="right" label="操作" width="150px" header-align="center" align="center">
            <template #default="scope">
              <el-button link type="warning" size="small"
                @click="router.push({ name: 'editInBound', params: { id: scope.row.id } })">编辑</el-button>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div><br />

      <!-- 分页 -->
      <div class="page-div" v-if="pageInfo != null">
        <el-pagination :current-page="pageNum" :page-size="pageSize" :total="pageInfo.total"
          @current-change="changePage" layout="total, ->, prev, pager, next, jumper" background />
      </div>
    </div>

  </div>
</template>

<script setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { ref, inject, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus'
let axios = inject("axios")
//获取公司
// let company = sessionStorage.getItem("companyCode");
// let company = "CNY001" //测试用 应该是通过jwt获取到相关信息。防止被篡改
//入库单表格数据
let inboundList = ref([]);
//分页相关数据  - page
let pageInfo = ref(null);
let pageNum = ref(1), pageSize = ref(10);
const router = useRouter();

// 搜索表单
const formInline = ref({
  keyword: "",
  type: '',
  staffId: '',
  dateRange: [],
  providerCode: '',
});
const shortcuts = [
  {
    text: "最近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
];


const loading = ref(false);

//顶部表单搜索查询  - search
function onSubmit() {
  if (loading.value) return;
  loading.value = true;

  console.log(formInline.value);
  axios.post('/xyy/inbound/page/staff', {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    // companyCode: company,
    //搜索表单中的信息
    keyword: formInline.value.keyword,
    beginTime: formInline.value.dateRange == null ? null : formInline.value.dateRange[0],
    endTime: formInline.value.dateRange == null ? null : formInline.value.dateRange[1],
    type: formInline.value.type,
    staffNo: formInline.value.staffNo
  }).then(res => {
    pageInfo.value = res.data.pageInfo;
    inboundList.value = res.data.pageInfo ? res.data.pageInfo.list : null
    console.log("pageInfo---:", pageInfo);
  }).finally(() => {
    loading.value = false;
  })
}

function changePage(nowPage) {
  pageNum.value = nowPage;
  onSubmit();
}

onMounted(() => {
  onSubmit();
})

const showInboundStatus = (status) => {
  let res = '';
  switch (status) {
    case 0: res = "已打回"; break;
    case 1: res = "已创建"; break;
    case 2: res = "已提交"; break;
    case 3: res = "已审核"; break;

  }
  return res;
}
const showInboundType = (type) => {
  let res = '';
  switch (type) {
    case 0: res = "其他入库"; break;
    case 1: res = "采购入库"; break;
    case 2: res = "退货入库"; break;
    case 3: res = "调拨入库"; break;
    case 4: res = "盘盈入库"; break;
  }
  return res;
}

let selectedOrder = ref([]);
const handleSelectionChange = (selected) => {
  selectedOrder.value = selected;
}
// 删除
const deleteInboundList = () => {
  if (!selectedOrder.value || selectedOrder.value.length == 0) {
    ElMessage({ message: "请选择要删除的入库单", type: 'warning', });
    return;
  }
  let delIdList = [], delCodeList = [];
  let canNotDelArr = [];
  selectedOrder.value.forEach(i => {
    if (i.status >= 2) {
      canNotDelArr.push({ code: i.code, status: i.status });
    } else {
      delIdList.push(i.id);
      delCodeList.push(i.code);
    }
  })
  console.log("delCodeList", delCodeList);
  console.log("canNotDelArr", canNotDelArr);
  if (delIdList && delIdList.length > 0) {
    const params = new URLSearchParams();
    delIdList.forEach(id => {
      params.append('ids', id); // 多次 append 相同 key，Spring 能识别为 List
    });
    axios({
      url: '/xyy/inbound/deleteList',
      method: 'post',
      data: params,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then(rs => {
      if (rs.data.code == 5200) {
        let mes = ``;
        delCodeList.forEach(i => {
          mes += `入库单<span style="color:black">${i}</span><span style="color:green">删除成功</span><br/><br/>`;
        })
        if (canNotDelArr && canNotDelArr.length > 0) {
          canNotDelArr.forEach(i => {
            mes += `入库单${i.code}<span style="color:red">删除失败</span>,因为该入库单${showInboundStatus(i.status)}<br/><br/>`
          })
        }
        ElMessage({
          dangerouslyUseHTMLString: true,
          message: mes,
        })
        onSubmit();
      } else {
        ElMessage({ message: "系统异常，本次删除失败", type: 'warning', });
      }
    })
  }
  if (canNotDelArr && canNotDelArr.length > 0) {
    let mes = '';
    canNotDelArr.forEach(i => {
      mes += `入库单<span style="color:black">${i.code}</span><span style="color:red">删除失败</span>,因为该入库单<span style="color:black">${showInboundStatus(i.status)}<br/>`
    })
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: mes,
    })
  }


}


function exportFile() {
  axios({
    url: '/xyy/download/inbound',
    method: 'post',
    data: {
      // 你的查询参数，例如：
      code: 'CK20251115',
      type: 1,
      status: 1
    },
    responseType: 'blob'  // 告诉 axios 返回的是二进制文件
  }).then(response => {
    // 创建 blob 对象
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });

    // 创建下载链接
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = '入库单列表.xlsx'; // 自定义文件名

    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 释放内存
    window.URL.revokeObjectURL(link.href);
  }).catch(error => {
    console.error('导出失败:', error);
  });
}

// 审核 -- 按理来说审核应该进入页面查看后才能审核，并且点击审核应该弹出一个对话框，合格/打回。
// const auditorInboundList = () => {
//   //判断是否可以审核
//   if (!selectedOrder.value || selectedOrder.value.length == 0) {
//     ElMessage({ message: "请选择要审核的入库单", type: 'warning', });
//     return;
//   }

//   let auditorIdList = [], delCodeList = [];
//   let canNotAuditorArr = [];
//   selectedOrder.value.forEach(i => {
//     if (i.status != 2) {
//       canNotDelArr.push({ code: i.code, status: i.status });
//     } else {
//       delIdList.push(i.id);
//       delCodeList.push(i.code);
//     }
//   })
//   console.log("delCodeList", delCodeList);
//   console.log("canNotDelArr", canNotDelArr);
//   if (delIdList && delIdList.length > 0) {
//     const params = new URLSearchParams();
//     delIdList.forEach(id => {
//       params.append('ids', id); // 多次 append 相同 key，Spring 能识别为 List
//     });
//     axios({
//       url: '/xyy/inbound/deleteList',
//       method: 'post',
//       data: params,
//       headers: {
//         'Content-Type': 'application/x-www-form-urlencoded'
//       }
//     }).then(rs => {
//       if (rs.data.code == 5200) {
//         let mes = ``;
//         delCodeList.forEach(i => {
//           mes += `入库单<span style="color:black">${i}</span><span style="color:green">删除成功</span><br/><br/>`;
//         })
//         if (canNotDelArr && canNotDelArr.length > 0) {
//           canNotDelArr.forEach(i => {
//             mes += `入库单${i.code}<span style="color:red">删除失败</span>,因为该入库单${showInboundStatus(i.status)}<br/><br/>`
//           })
//         }
//         ElMessage({
//           dangerouslyUseHTMLString: true,
//           message: mes,
//         })
//         onSubmit();
//       } else {
//         ElMessage({ message: "系统异常，本次删除失败", type: 'warning', });
//       }
//     })
//   }
//   if (canNotDelArr && canNotDelArr.length > 0) {
//     let mes = '';
//     canNotDelArr.forEach(i => {
//       mes += `入库单<span style="color:black">${i.code}</span><span style="color:red">删除失败</span>,因为该入库单<span style="color:black">${showInboundStatus(i.status)}<br/>`
//     })
//     ElMessage({
//       dangerouslyUseHTMLString: true,
//       message: mes,
//     })
//   }

// }
</script>

<style scoped>
/* 隐藏所有滚动条 */
body {
  overflow: -moz-scrollbars-none;
  /* 旧版Firefox */
  -ms-overflow-style: none;
  /* IE和Edge */
}

body::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}

.search-form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  /* 删除 white-space: nowrap */
}

/* 修复 inline 表单的默认间距 */
:deep(.el-form--inline .el-form-item) {
  margin-bottom: 0 !important;
  margin-right: 12px;
}

/* 控制 input 和 date-picker 宽度 */
:deep(.el-input),
:deep(.el-date-editor) {
  width: 180px;
}

/* 时间范围选择器宽度固定 */
:deep(.el-date-editor[type="datetimerange"]) {
  width: 340px !important;
}

/* 紧凑型标签字体大小 */
:deep(.el-form-item__label) {
  font-size: 14px;
  color: #555;
  padding-right: 6px;
}

/* 操作按钮组 */
.operate-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 10px;
  flex-wrap: wrap;
  /* 小屏时换行 */
}

/* 响应式：小屏下堆叠布局 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    gap: 10px;
  }

  :deep(.el-form--inline .el-form-item) {
    width: 100%;
    margin-right: 0 !important;
  }

  :deep(.el-input),
  :deep(.el-date-editor) {
    width: 100% !important;
  }
}

.operate-buttons {
  /*     flex-direction: column;
    align-items: flex-end; */
  margin-bottom: 10px;
}


/* 对话框展示动画-slide */
:global(.custom-dragging-style.is-dragging) {
  border: 2px dashed var(--el-color-primary);
  opacity: 0.65;
}


/* 表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 标签字体 */
:deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

/* 下拉框样式 */
:deep(.el-select .el-input__inner) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.2s;
}

:deep(.el-select .el-input__inner:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

/* 按钮样式 */
.dialog-footer {
  text-align: right;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer .el-button {
  padding: 8px 20px;
  font-size: 14px;
  border-radius: 6px;
}

.dialog-footer .el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
  color: white;
}

.dialog-footer .el-button--primary:hover {
  background-color: #096dd9;
}
</style>